


import { Button, Dialog } from "@material-tailwind/react";

import Image from 'next/image';
import styles from './validateDialog.module.css'
import { useState, useRef, useEffect } from "react";
import {  message } from 'antd';

import VideoRecorder from "./VideoRecorder";
import { postHttpQuestImg } from "@/utils/requestFn";


export default function ValidateDialogCom({
    userId,
    isModalVisible,
    setIsModalVisible,
    verificationStatus
}: {
    userId: string;
    isModalVisible: boolean;
    setIsModalVisible: (status: boolean) => void;
    verificationStatus: (status: boolean) => void;
}) {


    const videoRef = useRef(null);
    const countTimer = useRef(null);
    const webSocketRef = useRef(null);

    const [step, setStep] = useState(0);
    const [videoUrl, setVideoUrl] = useState('');

    const [readNum, setReadNum] = useState('')

    const verify_video = 'wss://120.77.1.222:9876/api/verify_code'





    useEffect(() => {
        const webSocket = new WebSocket(verify_video);
        webSocketRef.current = webSocket;

        webSocket.onopen = () => {
            // setIsRecording(true);
            console.log('WebSocket connection opened');
            webSocket.send(JSON.stringify({
                'user_id': '24518444659',
            }));

        };

        webSocket.onmessage = (event) => {
            console.log('Received message:', event.data);
            // alert(event.data);
            // Received message: {"code":200,"message":"success","data":{"valid":1,"valid_code":["3","0","3","1","3","4"],"valid_msg":"成功"}}
            let data = JSON.parse(event.data);

            console.log('data', data)
            if (data?.data?.type === 'verify_code_and_face') {
                if (data?.data?.valid === 1) {
                    // alert('恭喜通过人脸');
                    verificationStatus(false)
                } else {
                    // alert('人脸识别失败，请重新确认');
                    verificationStatus(false)
                    message.open({
                        type: 'error',
                        content: '人脸识别失败，请重新确认',
                    });


                }
            }
        };

    }, [])


    // 完成上传
    const completeUpload = (url: any) => {
        console.log('url', url)
        webSocketRef.current.send(url);
        setIsModalVisible(false);
        verificationStatus(true)

    }



    const validateFn = async () => {

        const formData = new FormData();
        formData.append('user_id', userId);
        formData.append('step', '2');
        const result = await postHttpQuestImg('/api/get_verification_code', formData);

        console.log('result', result)
        if (result.data.code) {
            setReadNum(result.data.code.join(''))
        }

        setStep(1);

    }




    return (
        <Dialog
            open={isModalVisible}
            size={"xxl"}
            animate={{
                mount: { y: 0 },
                unmount: { y: 5 },
            }}
            handler={() => setIsModalVisible(false)} placeholder={undefined} onPointerEnterCapture={undefined} onPointerLeaveCapture={undefined}            >
            <div className=" h-screen relative">
                <div className={`${step === 0 ? '' : 'hidden'}`}>
                    <div className={styles.img}>
                        <div className={styles['img-bg']}></div>
                        <div className={styles['img-line']}></div>
                        <Image
                            src={'/images/img/face_tips4.png'}
                            alt="Example"
                            className={``}
                            width={622}
                            height={370}
                        />
                    </div>
                    <div className="px-5">
                        <p className="text-center text-sm text-secondaryTextColor py-2">请根据文字提示，按数字顺序</p>
                        <p className="text-center text-sm text-secondaryTextColor py-2">录制 <span className="text-danger">1-10秒</span> 视频</p>
                        <p className="text-center text-sm text-secondaryTextColor py-2">请正对手机摄像头，确保面部光源充足</p>
                    </div>
                    <div className=" fixed z-50 bottom-5  left-0 w-full px-6">
                        <Button variant="filled" onClick={validateFn} className={`bg-mainColor text-white p-3 text-center  rounded-full w-full text-sm `} placeholder={'undefined'} onPointerEnterCapture={undefined} onPointerLeaveCapture={undefined}>
                            开始验证
                        </Button>
                    </div>
                </div>
                <div className={`${step === 1 ? '' : 'hidden'}`}>
                    <VideoRecorder completeUpload={completeUpload} readNum={readNum} />
                </div>
            </div>
        </Dialog>
    )
}